#coding=utf-8
import struct
import io
import matplotlib.pyplot as plt

tx_current =[]
rx_voltage =[]
tx_voltage = []
header_count = 0
datas_main = None
packet_lens = 0

def EntiretyDecodeStructByteBack(data):
    items = bytes(b % 256 for b in data)
    ##print("---------EntiretyDecodeStructByteBack == ")
    ##print(items)
    return len(items)

def _recv_unsigned_int(value):
    data = struct.unpack("<H",value)[0]
    ##print("----------------------------_recv_unsigned_int == ")
    ##print(data)
    return data

def _recv_float(value):
    ##print("----------------------------_recv_float == "+str(value))
    data = struct.unpack("<f",value)[0]
    ##print("----------------------------_recv_float == ")
    ##print(data)
    return data

def EntiretyDecodeStructByte(data):

    items = data
    global datas_main
    datas_main = bytes(b % 256 for b in items)


def EntiretyDecodeStructByte11(data):
    ##print("----------------------- EntiretyDecodeStruct0 开始 --------------------------------")
    items = data
    global datas_main
    datas_main = bytes(b % 256 for b in items)


def SetPageLens(data):
    global packet_lens
    packet_lens = data
def pb2jb(byte_arr):
    """
    python字节码转java字节码
    :param byte_arr:
    :return:
    """
    return [int(i) - 256 if int(i) > 127 else int(i) for i in byte_arr]
def jb2pb(byte_arr):
    """
    java 字节码转python字节码
    :return:
    """
    return [i + 256 if i < 0 else i for i in byte_arr]

def sendCurve(rx_voltage):
    plt.figure(figsize=(24,8))
    plt.plot(rx_voltage,'g', label='tx_vol')
    plt.xlabel('count')
    #plt.ylabel('Y')
    plt.title('Simple Scatterplot')
    #plt.grid(True) ##??????
    plt.pause(0.5)
    f = io.BytesIO()
    plt.savefig(f, format="png")
    return f.getvalue()

def sendCurveJava(rx_voltage):
    data = jb2pb(rx_voltage)
    plt.figure(figsize=(24,8))
    plt.plot(data,'g', label='tx_vol')
    plt.xlabel('count')
    #plt.ylabel('Y')
    plt.title('Simple Scatterplot')
    #plt.grid(True) ##??????
    plt.pause(0.5)
    f = io.BytesIO()
    plt.savefig(f, format="png")
    return f.getvalue()

def recv_unsigned_int(value):
    return struct.unpack('<H',value)[0]
def recv_float(value):
    return struct.unpack('<f',value)[0]
def recv_short(value):
    print("value = ",value)
    return struct.unpack('h',value)[0]
def EntiretyDecodeStructChar(data):
    lis =[]
    lis = data.lstrip("0,Success;").encode("ascii")
    #print(lis)
    #print("----------------------- EntiretyDecodeStruct_char 结束 --------------------------------")
def DecodeStruct(data):
    ##print("----------------------- DecodeStruct_data 开始 --------------------------------")
    #print(data)
    ascData = data.replace("/", "").replace(";", "").strip().encode("utf-8");
    #print(len(ascData))
    if len(ascData) == 2:
        #print(ascData)
        datas = struct.unpack('h', ascData)[0]

        ##print("----------------------- DecodeStruct 结束--------------------------------" + str(datas))
    elif len(ascData) == 1:
        ##print(struct.pack('h',315))
        ascData = data.replace("/", "").encode("ISO8859-1");
        #print(ascData)
        #print(len(ascData))
        if len(ascData) == 1:
            #print(struct.pack('h',303))
            ascData = data.encode("ISO8859-1");
            datas = struct.unpack('c', ascData)[0]
            #print(datas)
        elif len(ascData) == 2:
            datas = struct.unpack('<H', ascData)[0]
            #print(datas)
    else:
        ##print(" indx, error when tx_voltage, break" )
        #print(struct.pack('h',511))
        #ascData = data.encode("ascii");
        ascData = data.encode("ISO8859-1");
        #print(ascData)

        datas = struct.unpack('<H', ascData)[0]
    return datas
def DecodeByteStruct(data):
    # #print("----------------------- DecodeByteStruct_data 开始 --------------------------------")
    ascData = data.replace("/", "").replace(";","").encode("ascii");
    datas = struct.unpack('H', ascData)[0]
   # #print("----------------------- DecodeByteStruct_data 结束--------------------------------"+str(datas))
    return datas
def DecodeIntStruct(data):
    ##print("----------------------- DecodeIntStruct 开始 --------------------------------")
    ##print(data)
    # #print(type(data))
    datas = None
    ascData = data.encode("utf-8");
    ##print(ascData)
    if ascData == b'\x00\x00':
        index = struct.unpack("<H", ascData)[0]
        ##print("b'\x00\x00' ======= " + str(index))
        return ""

    else:
        ascData = data.replace("/", "").replace(";", "").strip().encode("ISO8859-1");
       # #print("--------------------len ="+str(len(ascData)))
        if len(ascData) == 4:
         #   #print("--------------------len == 4")
            datas = struct.unpack('<i', ascData)[0]
        else:
            #ascData = data.replace("(", "").replace(")","").replace(",","").encode("ISO8859-1");
           # #print("--------------------len > 4 ------"+str(ascData)+" -------"+str(type(ascData)))
            if ascData == b'U\xaa':
                datas = struct.unpack('<H', ascData)[0]
            elif ascData == b'\x00\x00':
                datas = struct.unpack("<H", ascData)[0]
                #print("b'\x00\x00' ======= " + str(datas))
            else:
                ascData = data.replace("/", "").replace(";", "").strip().encode("ascii");
                datas = struct.unpack('i', ascData)[0]
    ##print(type(ascData))
   # #print(datas)
    ##print("----------------------- DecodeIntStruct 结束--------------------------------")

    return datas
def DecodeUtfStruct(data):
    # #print("----------------------- DecodeUtfStruct 开始 --------------------------------")
    ascData = data.replace("(", "").replace(")","").replace(",","").encode("ISO8859-1");
    # #print(ascData)
    datas = struct.unpack('<H', ascData)[0]
    ##print("----------------------- DecodeUtfStruct 结束--------------------------------")
    ##print(hex(datas))
    return hex(datas)

def DecodeTxVStruct(data,indx):
    ##print("----------------------- DecodeTxVStruct 开始 --------------------------------")
    # #print(data)
    datas = None
    ascData = data.encode("utf-8");
    # #print(ascData)

    ascData = data.replace("/", "").strip().encode("ISO8859-1");
    # #print("--------------------len ="+str(len(ascData)))
    # #print(ascData)

    if len(ascData) == 4:
        ##print("--------------------len == 4")
        datas = struct.unpack('<f', ascData)[0]
    else:
        ##print(str(indx) + " indx, error when tx_voltage, break" )
        datas = "null"

    ##print(type(ascData))
    ##print(datas)
    ##print("----------------------- DecodeTxVStruct 结束--------------------------------")

    return datas

def DecodeTxCStruct(data,indx):
    ##print("----------------------- DecodeTxCStruct 开始 --------------------------------")
    # #print(data)
    datas = None
    ascData = data.encode("utf-8");
    # #print(ascData)

    ascData = data.replace("/", "").strip().encode("ISO8859-1");
    # #print("--------------------len ="+str(len(ascData)))
    # #print(ascData)

    if len(ascData) == 4:
        ##print("--------------------len == 4")
        datas = struct.unpack('<f', ascData)[0]
    else:
        ##print(str(indx) + " indx, error when tx_voltage, break" )
        datas = "null"

    ##print(type(ascData))
    ##print(datas)
    ##print("----------------------- DecodeTxCStruct 结束--------------------------------")

    return datas
def DecodeRxVStruct(data,indx):
    ##print("----------------------- DecodeRxVStruct 开始 --------------------------------")
    ##print(data)
    datas = None
    ascData = data.encode("utf-8");
    ##print(ascData)

    ascData = data.replace("/", "").strip().encode("ISO8859-1");
    ##print("--------------------len ="+str(len(ascData)))
    ##print(ascData)

    if len(ascData) == 4:
        ##print("--------------------len == 4")
        datas = struct.unpack('<f', ascData)[0]
    else:
        ##print(str(indx) + " indx, error when tx_voltage, break" )
        datas = "null"

    ##print(type(ascData))
    ##print(datas)
    ##print("----------------------- DecodeRxVStruct 结束--------------------------------")

    return datas

def DecodeSystemInform(data):
    ascData = data.replace("/", "").strip().encode("ISO8859-1");

    datas = struct.unpack('<f', ascData)[0]
    #print(datas)
    return round(datas,1)

def DecodeSystemInformInt(data):
    return struct.unpack('<H',data.encode("ISO8859-1"))[0]


